import { BizKfExtraProColumnType } from '@/components';
import {Divider, message, Space, Tag, Typography} from 'antd';
import {
  convertKfEnumsToProTableValueEnum,
  KfModal,
  KfPagingTablePage,
  KfPagingTablePagePropsAction,
  useBackendEnum,
} from 'kf-web-library';
import React, { useRef, useState } from 'react';
import QuickGroupForm from './components/QuickForm';
import * as API from '@/services';
import { useAccess } from '@@/exports';

type Entity = API.Group_TreeNode;
type EntityPageQueryParams = API.GroupTreeQueryParams;
const entityTypeName = '组织机构';
const EntityQuickForm = QuickGroupForm;

interface EntityTableListProps {}

/**
 * 组织列表
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const { enumDict, getBackendEnum } = useBackendEnum();
  const access = useAccess();
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();

  const [expandedRowKeys, setExpandedRowKeys] = useState<any>([]);

  return (
    <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
      actionRef={actionRef}
      entityTypeName={entityTypeName}
      pagingQuery={(params) =>
        API.queryGroupTree(params).then((resp) => {
          /*if (resp.flag) {
                    /!**
                     * 默认都展开
                     *!/
                    const expandKeys: string[] = []
                    treeWalk(resp.data, (node) => {
                        expandKeys.push(node.id.toString());
                    })
                    setExpandedRowKeys(expandKeys);
                }*/
          return new Promise((resolve) => resolve(resp as API.RespPageResult<Entity>));
        })
      }
      opActionsDef={{
        single: {
          /* deleteOne: (record) => {
                       KfModal.deleteConfirm(record.id as string, () => {
                         service.deleteGroup(record.id!).then((res) => {
                           if (res.flag) {
                             message.info('删除成功');
                             actionRef.current?.reload();
                           }
                         });
                       });
                     },*/
        },
        multi: {
          /*deleteMultiple: (records) => {
                      KfModal.batchActionConfirm("删除", records.length, () => {
                        service.deleteGroups(records.map((r) => r.id!)).then((res) => {
                          if (res.flag) {
                            message.info('批量删除成功');
                            actionRef.current?.reload();
                          }
                        });
                      });
                    },*/
        },
      }}
      opFloatingsDef={{
        noargs: {
          /*createModal: () => ({
                      title: `新建${entityTypeName}`,
                      content: <EntityQuickForm formType={'create'}/>,
                    }),*/
        },
        single: {
          modifyModal: (record) => ({
            title: `编辑${entityTypeName}`,
            content: <EntityQuickForm formType={'modify'} bizId={record.id} />,
          }),
          viewModal: (record) => ({
            title: `查看${entityTypeName}`,
            content: <EntityQuickForm formType={'view'} bizId={record.id} />,
          }),
        },
      }}
      proTable={{
        indentSize: 10,
        search: false,
        pagination: false,
        expandedRowKeys: expandedRowKeys,
        onExpandedRowsChange: setExpandedRowKeys,
      }}
      columns={[
        {
          title: '组织名称',
          dataIndex: nameof<Entity>((x) => x.name),
          sorter: false,
          hideInSearch: false,
          ellipsis: true,
        },
        {
          title: '组织角色',
          width: 230,
          ellipsis: true,
          dataIndex: nameof<Entity>((x) => x.roles),
          hideInSearch: true,
          renderText: (_, record) => {
            return (
              <div>
                {record.roles?.sort().map((d, dindex) => (
                  <Tag key={dindex} color="geekblue">
                    {d.name}
                  </Tag>
                ))}
              </div>
            );
          },
        },
        /*{
                    title: '所在地区',
                    width: 100,
                    ellipsis: true,
                    dataIndex: nameof<Entity>((x) => x.area),
                    hideInSearch: false,
                    renderText: (text, record) => {
                        return record.area?.name;
                    },
                },*/
        {
          title: '组织类型',
          width: 160,
          dataIndex: nameof<Entity>((x) => x.type),
          sorter: false,
          hideInSearch: false,
          filters: undefined,
          formItemProps: {
            allowClear: true,
          } as any,
          ellipsis: true,
          valueEnum: convertKfEnumsToProTableValueEnum(enumDict['GroupType']),
        },
        /*{
                    title: '备注',
                    width: 100,
                    ellipsis: true,
                    dataIndex: nameof<Entity>(x => x.description),
                    hideInSearch: false,
                },*/
        {
          title: '操作',
          fixed: 'right',
          width: 130,
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record: any) => (
            <Space  size={0} split={<Divider type="vertical" />}>
              <a onClick={() => actionRef.current?.openFloating.single?.viewModal(record)}>查看</a>
              {access.hasAnyAuthority('ROLE_ADMIN', 'ROLE_NODE_ADMIN') && (
                <>
                  <a onClick={() => actionRef.current?.openFloating.single?.modifyModal(record)}>
                    编辑
                  </a>
                  <a onClick={() => actionRef.current?.executeAction.single?.deleteOne(record)}>
                    <Typography.Text type="danger">删除</Typography.Text>
                  </a>
                </>
              )}
            </Space>
          ),
        },
      ]}
    />
  );
};

export default EntityTableList;
